package dao;

import com.mongodb.client.MongoCollection;
import entity.Admin;
import entity.User;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import util.MongoDBUtil;
import util.MorphiaUtil;

public class AdminDAO {
    //根据id查询
    public Admin findById(String id) {
        Datastore ds = MorphiaUtil.getDB();
        Query<Admin> query = ds.createQuery(Admin.class);
        query.filter("_id",new ObjectId(id));
        Admin admin = query.get();
        return admin;
    }
    //根据name查询
    public Admin findByName(String name) {
        Datastore ds = MorphiaUtil.getDB();
        Query<Admin> query = ds.createQuery(Admin.class);
        query.filter("name",name);
        Admin admin = query.get();
        return admin;
    }

    public void insert(User user) {
        //连接mongo的database 获取collection
        MongoCollection<Document> users = MongoDBUtil.getCollection("admin");
        //将对象转换为document
        Document doc = new Document();
        doc.put("name", user.getUsername());
        doc.put("pwd", user.getPassword());
//        doc.put("age", user.getAge());
        //执行insertOne
        users.insertOne(doc);
    }
}
